package com.mall.b2c.service.impl;

import com.mall.b2c.bean.GoodsBuyRecordBean;
import com.mall.b2c.bean.IntergralShopProductBean;
import com.mall.b2c.dao.IntergralShopProductDao;
import com.mall.b2c.domain.intergral.ShopProductDomain;
import com.mall.b2c.service.IntergralShopProductService;
import com.mall.common.bean.Order;
import com.mall.common.exception.NoticeException;
import com.mall.common.hibernate.Finder;
import com.mall.common.service.impl.BaseServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by chen on 16/12/15.
 */
@Service
@Transactional
public class IntergralShopProductServiceImpl extends  BaseServiceImpl<ShopProductDomain, Long> implements IntergralShopProductService{

    @Resource
    public void setBaseDao(IntergralShopProductDao productDao) {
        super.setBaseDao(productDao);
    }


    @Override
    public List<IntergralShopProductBean> getShoproductList(Long id, String orderBy) {
        Finder finder = Finder.create("select new com.mall.b2c.bean.IntergralShopProductBean(bean) from ShopProductDomain bean where 1=1");
        if(id!=null){
            finder.append(" and bean.shopclass.id = (:id)");
            finder.setParam("id", id);
        }

        if(StringUtils.isNotBlank(orderBy)){
            String fieldName = orderBy.split(" ")[0];
            String direction  = orderBy.split(" ")[1];
            finder.setOrder(new Order(fieldName, Order.Direction.valueOf(direction)));
        }
        return finder.findHQLList();
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void exchange(  ShopProductDomain productDomain,int num){
        String hql = "update ShopProductDomain bean set bean.sale_num=bean.sale_num+:num where bean.id=:id and bean.sale_num<bean.num-:num";
        int result = getEntityManager().createQuery(hql).setParameter("id",productDomain.getId()).setParameter("num", num).executeUpdate();
        if(result<0){
           throw  new NoticeException("商品不足");
        }
    }
}





